package com.bq.gametrade.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.dialog.LoadingProgressDialog;
import com.bq.gametrade.utils.NetworkUtils;
import com.bq.gametrade.utils.SharedPreferencesUtils;
import com.bq.gametrade.utils.StringUtils;
import com.bq.gametrade.view.PayPasswordValidationView;

import java.util.HashMap;
import java.util.Map;

public class TransferActivity extends BaseActivity implements View.OnClickListener {

    private ImageView back;
    private TextView tvTitle, tvTransferBill;
    private TextView tvAccountMoney, tvAccountYuQuan;
    private EditText etTransferAccount, etTransferMoney;
    private LinearLayout layClear;
    private Button btnTransfer;
    private RadioGroup radioGroup;
    private RadioButton radioButton;
    private String transferType = "";
    private ImageView ivFriend;
    private LoadingProgressDialog progressDialog;
    private UserInfoDetails userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer);
        progressDialog = new LoadingProgressDialog(this,"正在转账···");
        if(application.isLogin()){
            userInfo = application.getUserInfo();
        }else {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        initView();
    }

    private void initView() {
        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        tvTitle = serchViewById(R.id.title_name);
        tvTitle.setText("转账");
        tvTransferBill = serchViewById(R.id.tv_transferBill);
        tvTransferBill.setOnClickListener(this);
        tvAccountMoney = serchViewById(R.id.tv_accountYue);
        tvAccountYuQuan = serchViewById(R.id.tv_accountYuQuan);
        tvAccountMoney.setText(application.getUserInfo().userMoney + " 元");
        tvAccountYuQuan.setText(application.getUserInfo().userCard + " 个");
        layClear = serchViewById(R.id.lay_clear);
        layClear.setOnClickListener(this);

        etTransferAccount = serchViewById(R.id.et_transferAccount);
        etTransferMoney = serchViewById(R.id.et_transferMoney);
        etTransferMoney.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        etTransferMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        etTransferMoney.setText(s);
                        etTransferMoney.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    etTransferMoney.setText(s);
                    etTransferMoney.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etTransferMoney.setText(s.subSequence(0, 1));
                        etTransferMoney.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etTransferAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (etTransferAccount.getText().toString().length() > 0) {
                    layClear.setVisibility(View.VISIBLE);
                } else {
                    layClear.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        String str = (String) SharedPreferencesUtils.getValue(TransferActivity.this, SharedPreferencesUtils.transfer_account, "");
        if (!str.equals("")) {
            etTransferAccount.setText(str);
            etTransferAccount.setSelection(etTransferAccount.length());
        }

        radioGroup = serchViewById(R.id.rg_pay);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                radioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
                if (radioButton.getText().toString().equals("转余额")) {
                    transferType = "1";
                } else {
                    transferType = "0";
                }
            }
        });

        btnTransfer = serchViewById(R.id.btn_transfer);
        btnTransfer.setOnClickListener(this);
        ivFriend = serchViewById(R.id.iv_friend);
        ivFriend.setOnClickListener(this);

    }

    private void setTransferAccount(String account,String nickName){
        if(!TextUtils.isEmpty(account)){
            etTransferAccount.setText(account);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.iv_friend:
                startActivityForResult(new Intent(TransferActivity.this,TransferContactsActivity.class),1);
                break;
            case R.id.lay_clear:
                etTransferAccount.setText("");
                break;
            case R.id.tv_transferBill:
                startActivity(new Intent(TransferActivity.this, TransferBillActivity.class));
                break;
            case R.id.btn_transfer:
                if (TextUtils.isEmpty(etTransferAccount.getText().toString())) {
                    toastShow("转账账号还没有输入");
                    return;
                }

                if (TextUtils.isEmpty(etTransferMoney.getText().toString())) {
                    toastShow("转账金额还没有输入");
                    return;
                }
                if (etTransferMoney.getText().toString().equals("0")) {
                    toastShow("转账金额不正确");
                    return;
                }
                if (transferType.equals("")) {
                    toastShow("转账类型还没有选择");
                    return;
                }
                if (etTransferAccount.getText().toString().equals(application.getUserInfo().account)||
                        etTransferAccount.getText().toString().equals(application.getUserInfo().bqAccount)) {
                    toastShow("您不能给自己转账");
                    return;
                }
                if (Double.parseDouble(etTransferMoney.getText().toString()) <= 0) {
                    toastShow("输入转账金额有误");
                    return;
                }
                if (transferType.equals("1") && Double.parseDouble(etTransferMoney.getText().toString()) > Double.parseDouble(application.getUserInfo().userMoney)) {
                    //转余额判断
                    toastShow("您没有那么多的余额了，快去充值吧");
                    return;
                }
                if (transferType.equals("0") && !StringUtils.isInteger(etTransferMoney.getText().toString())) {
                    //转余额判断
                    toastShow("转账鱼券必须为整数");
                    return;
                }

                if (transferType.equals("0") && Double.parseDouble(etTransferMoney.getText().toString()) > Double.parseDouble(application.getUserInfo().userCard)) {
                    //转余额判断
                    toastShow("您没有那么多的鱼券了，快去充值吧");
                    return;
                }
                if (!NetworkUtils.isNetworkAvailable(TransferActivity.this)) {
                    toastShow("当前网络异常");
                    return;
                }
               toPay(transferType);
                break;

        }
    }


    /**
     * 验证支付密码-----start
     */

    private void toPay(final String mType){
        final PayPasswordValidationView payPasswordValidationView = new PayPasswordValidationView(TransferActivity.this,userInfo,progressDialog);
        payPasswordValidationView.showAtLocation(TransferActivity.this.findViewById(R.id.activity_transfer),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        payPasswordValidationView.backgroundAlpha(0.6f);
        payPasswordValidationView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                payPasswordValidationView.backgroundAlpha(1f);
            }
        });

        payPasswordValidationView.setOnFinishInputPayPassword(new PayPasswordValidationView.OnPayPasswordInputFinish() {
            @Override
            public void inputFinish(String status) {
                if (status.equals("0")) {
                    toTransfer(mType);
                }
            }
        });
    }

    /**
     * end
     **/

    private void closeDialog(){
        if(progressDialog !=null){
            progressDialog.dismiss();
        }
    }


    private void toTransfer(String type) {
        Log.e("wu",etTransferMoney.getText().toString());
        /**
         * 1:转账余额
         * 2：转账鱼券
         */
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("account", etTransferAccount.getText().toString());
        params.put("num", etTransferMoney.getText().toString());
        params.put("type", type);
        VRHttp.sendRequest(TransferActivity.this, HttpLink.TRANDFER_MONRY_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        toastShow("转账成功！");
                        SharedPreferencesUtils.saveValue(TransferActivity.this, SharedPreferencesUtils.transfer_account, etTransferAccount.getText().toString());
                        finish();
                    } else if (bean.status.equals("99")) {
                        toastShow("登录超时请重新登陆");
                        application.setUserInfo(null);
                        startActivity(new Intent(TransferActivity.this, LoginActivity.class));
                    } else if (bean.status.equals("98")) {
                        toastShow("您的账号已在其它设备登录，请重新登录修改您的密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(TransferActivity.this, LoginActivity.class));
                        finish();
                    } else {
                        toastShow("转账失败！");
                    }
                } else {
                    toastShow("转账失败！");

                }
            }
            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("转账失败！");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeDialog();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case 1:
                if (resultCode == RESULT_OK)
                {
                    String getFriendName = data.getStringExtra("friendName");
                    String getFriendAccount = data.getStringExtra("friendAccount");
                    setTransferAccount(getFriendAccount,getFriendName);
                }
                break;
            case 2:
                if (resultCode == RESULT_OK)
                {
                    String getData = data.getStringExtra("second");
                }
                break;
            default:
                break;
        }
    }
}
